<template>
  <el-dialog
    v-model="state.show"
    title="附件清单"
    width="60%"
    modal-class="finacial-file-dailog"
  >
    <div class="btn-box">
      <el-button type="default" icon="RefreshRight" style="margin-right: 5px">
      </el-button>
      <el-upload
        action=""
        :show-file-list="false"
        :http-request="submitUpload"
        ref="uploadEl"
      >
        <el-button type="primary" icon="plus"> 新增 </el-button>
      </el-upload>
    </div>

    <AppPageTable
      stripe
      :data="state.tableData"
      @change="getList"
      :height="'300'"
      :option="state.tableDataOption"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        fixed="left"
      />
      <el-table-column prop="originalName" label="文件名称" align="center">
      </el-table-column>
      <el-table-column align="center" label="文件大小">
        <template #default="scope">
          {{ scope.row.size }}
        </template>
      </el-table-column>
      <el-table-column prop="fileType" align="center" label="文件类型">
      </el-table-column>
      <el-table-column prop="createTime" align="center" label="文件日期">
      </el-table-column>
      <el-table-column prop="260" align="center" label="操作">
        <template #default="scope">
          <el-button link @click="delFile(scope.row)"> 删除 </el-button
          ><span style="color: rgba(0, 0, 0, 0.65); margin: 0 8px">|</span>
          <el-button link @click="previewImage(scope.row)"> 预览 </el-button>
          <span style="color: rgba(0, 0, 0, 0.65); margin: 0 8px">|</span>
          <el-button link @click="filesLoad(scope.row)"> 下载 </el-button>
        </template>
      </el-table-column>
    </AppPageTable>
  </el-dialog>
  <el-dialog
    v-model="state.imageShow"
    title="附件清单"
    width="60%"
    modal-class="image-dailog"
  >
    <img :src="state.imageUrl" alt="" class="image-container" />
  </el-dialog>
</template>

<script setup>
import { reactive, ref, onMounted, defineProps, defineEmits } from "vue";
import AppPageTable, { useTableOption } from "@/components/AppPageTable2";
import { getFIleType } from "@/public/publicUtils";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/public/request";
import { useRoute, useRouter } from "vue-router";

const Route = useRoute();

const props = defineProps({
  //保存是上传的文件
  attachmentList: {
    type: Array,
    default: () => [],
  },
});

const state = reactive({
  show: false,
  //表格数据
  tableData: [],
  tableDataTotal: [],
  tableDataOption: useTableOption(),
  //路由跳转传递的参数id
  id: "",
  // 图片地址
  imageUrl: "",
  imageShow: false,
  // 标记上产的文件index
  index: 0,
});

// 设置上传成功的文件数据的分页
const getList = () => {
  let page = state.tableDataOption.page;
  let pageSize = state.tableDataOption.pageSize;
  state.tableData = state.tableDataTotal.slice(
    (page - 1) * pageSize,
    page * pageSize
  );
};

// 打开文件上传
const open = () => {
  state.tableDataOption.page = 1;
  state.tableDataOption.pageSize = 10;
  state.show = true;
  for (const iterator of state.attachmentList) {
    iterator.fileType = getFIleType(iterator.contentType);
  }
  state.tableDataTotal = state.attachmentList;
  state.tableDataOption.total = state.attachmentList.length;
  getList();
};

// 删除文件
const delFile = async (row) => {
  let res = await request.post("/api/storage/delete", {
    idArray: [row.id],
  });
  if (res.status) {
    let index = -1;
    let copytableData = JSON.parse(JSON.stringify(state.tableDataTotal));
    for (let i = 0; i < copytableData.length; i++) {
      if (copytableData[i].id === row.id) {
        index = i;
        break;
      }
    }
    if (index !== -1) {
      state.attachmentList.splice(index, 1); // 通过splice()函数删除指定索引处的元素
      state.tableDataTotal = JSON.parse(JSON.stringify(state.attachmentList));
    }
    state.tableDataOption.total = state.attachmentList.length;
    getList();
    ElMessage.success("删除成功");
  } else {
    ElMessage.warning(res.message);
  }
};

// 预览图片
const previewImage = (row) => {
  const canPreviewType = ["png", "PNG", "jpg", "JPG"];
  if (canPreviewType.indexOf(row.fileType) != -1) {
    state.imageUrl = row.filePath;
    state.imageShow = true;
  } else {
    ElMessage.warning("附件中无图片，无法预览");
  }
};

//新增
const submitUpload = async (file) => {
  const accptFileType = [
    "doc",
    "docx",
    "xls",
    "xlsx",
    "pdf",
    "jpg",
    "jpeg",
    "png",
  ];
  let fileDetail = file.file;
  if (fileDetail.size / 1024 / 1024 > 5) {
    ElMessage.error("文件大小不能超过5MB!");
    return;
  }
  if (accptFileType.indexOf(getFIleType(fileDetail.type)) == -1) {
    ElMessage.error("上传文件受限");
    return;
  }
  let fileData = new FormData();
  fileData.append("file", file.file);
  fileData.append("FileType", "docCash");
  fileData.append("BusId", state.id);
  let res = await request.post("/api/storage/uploadbusfile", fileData);
  if (res.status) {
    ElMessage.success("上传成功");
    res.data.fileType = getFIleType(res.data.contentType);
    res.data.createTime = dayjs(res.data.createTime).format(
      "YYYY-MM-DD HH:mm:ss"
    );
    state.attachmentList.push(res.data);
    state.tableDataTotal = JSON.parse(JSON.stringify(state.attachmentList));
    state.tableDataOption.total = state.tableDataTotal.length;
    getList();
  } else {
    ElMessage.warning(res.message);
  }
};

// 文件下载
const filesLoad = async (row) => {
  const res = await request.downloadByPost("/api/storage/downloadfile", {
    Id: row.id,
  });
  const reg = /(?=filename\*=UTF-8'').*/;
  let filename = reg.exec(res.header["content-disposition"]);
  filename = decodeURI(filename[0].replace(/filename\*=UTF-8''/, ""));
  const url = URL.createObjectURL(res.blob);
  const a = document.createElement("a");
  a.id = "down-" + new Date().getTime();
  a.setAttribute("href", url);
  a.download = filename;
  a.click();
  URL.revokeObjectURL(a.href);
};

onMounted(() => {
  state.id = Route.query.id;
});
</script>

<style lang="scss">
.finacial-file-dailog {
  .el-dialog__header {
    border-bottom: 1px solid #e8e8e8;
  }

  .el-dialog {
    min-width: 630px;
  }

  .el-table--border th.el-table__cell {
    color: #606266;
    font-size: 14px;
    font-weight: 400;
    background-color: #f8f8f9 !important;
  }
}

.image-dailog {
  .el-dialog__header {
    .el-dialog__title {
      display: none;
    }
  }

  .el-dialog__body {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
<style lang="scss" scoped>
.btn-box {
  margin-top: 8px;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.image-container {
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
}
</style>
